import Vue from 'vue';
// 选部门和人员组件
import DepartmentAndUser from './DepartmentAndUser.vue';
// 选择部门组件
import Department from './Department.vue';
import i18n from '@src/locales';
/* util */
import Log from '@src/util/log.ts'
import { destroyComponent } from '@src/util/dom';
import fastCall from '@src/component/util/fastCall.ts'
import { isArray, isUndefined, isObject } from '@src/util/type'
import { randomString } from 'pub-bbx-utils'

import { useNewVue } from '@hooks/useNewVue'
const { createVue } = useNewVue();

const DepartmentAndUserComponent = Vue.extend(DepartmentAndUser);

function getDefaultOptions() {
  return {
    id: `base-user-${randomString(4)}-${randomString(4)}`
  }
}

function choose(type = 'dept', options = {}) {
  Log.succ(type, 'type', choose.name)
  
  if(type == 'dept' || type == 'team') return deptWithUser(options);
  if(type == 'dept_only') return department(options);
}

/** 部门和人员 */
function deptWithUser(options){
  // 处理传入参数
  let selectedUser = [];
  let max = options.max;
  
  if(
    ( typeof max == 'number' || typeof max == 'string' )
    && !isNaN(max) 
    && isFinite(max)
  ) {
    max = parseInt(max);
  } else {
    max = 0;
  }
  
  // 后端已经限制了人数，前端不应限制选人
  if (isArray(options.selected)) {
    selectedUser = max === 1 ? [] : options.selected;
  }
  
  if (isObject(options.selected)) {
    selectedUser = max === 1 ? [] : options.selected?.users || [];
  }
  
  let selectedDepts = []
  if (
    (options.showDeptCheckbox || options.showTeamCheckbox)
    && isArray(options?.selected?.depts || options?.selected?.teams)
  ) {
    selectedDepts = options?.selected?.depts || options?.selected?.teams || []
  }
  
  if (options.showDeptCheckbox && isArray(options.selectedDepts)) {
    selectedDepts = options.selectedDepts;
  }
  
  if (options.showTeamCheckbox && Array.isArray(options.selectedTeams)) {
    selectedDepts = options.selectedTeams
  }
  
  let showLocation = !!options.allotMap;
  let action = '/security/tag/userList' ;
  if(options.action) action = options.action;
  
  let instance = new DepartmentAndUserComponent({
    i18n,
    propsData: {
      title: options.title,
      selectedUser,
      selectedDepts,
      max,
      showTaskCount: options.showTaskCount === true,
      showUserState: options.showUserState === true,
      showLocation, // 是否显示定位信息
      lat: options.lat,
      lng: options.lng,
      action,
      isUserGuide: options.isUserGuide === true,
      showDeptCheckbox: options.showDeptCheckbox === true || options.showTeamCheckbox === true,
      seeAllOrg: options.seeAllOrg || false, /** 是否 只可见本团队成员 */
      departShow: options.departShow,
      showDeleteUser: options.showDeleteUser || false, // 是否显示离职人员
      top: isUndefined(options?.top) ? undefined : options.top,
      unique: isUndefined(options?.unique) ? undefined : options.unique,
      options: options?.options ? options.options : getDefaultOptions(),
      from: options?.from,
      typeServiceProvider: options?.typeServiceProvider, // 服务商 控制左边树 【0组织架构】 【1服务商】 【''全部】 默认和之前逻辑一样
      isJudge: options?.isJudge || '', // 是否验证被选中的人是不是主管  
      isNothing: options?.isNothing, // 高级搜索是否添加 无 字段
      isCalendar: options?.isCalendar, // 是否是日历模块
      calendarAction: options?.calendarAction, // 日历左侧树接口
      calendarSeeAllOrg: options?.calendarSeeAllOrg, // 日历左侧树接口
      isShowTag: options?.isShowTag, // 只显示tag表部门
    }
  });
  
  let ele = document.createElement('div');
  let body = document.body;
  let pending = false;
  
  return new Promise((resolve, reject) => {
    instance.$on('destroy', event => {
      setTimeout(() => destroyComponent(instance), 1500);
    })
    
    instance.$on('input', user => {
      if(pending) return;
      
      pending = true;
      resolve({ status: 0, data: user });
    });
    
    instance.$on('cancel', () => {
      if(pending) return;
      
      pending = true;
      resolve({ status: 1, message: 'cancel' });
    })
    
    body.appendChild(ele);
    instance.$mount(ele);
  })
}

/** 选择部门 */
function department( options = {} ){
  // 处理传入参数
  let max = options.max;
  
  if(
    ( typeof max == 'number' || typeof max == 'string' )
    && !isNaN(max) 
    && isFinite(max)
  ) {
    max = parseInt(max);
  } else {
    max = 0;
  }
  
  let selectedDepts = [];
  if(Array.isArray(options.selectedDepts)) {
    selectedDepts = options.selectedDepts;
  }
  let body = document.body;
  let mountEl = options.mountEl instanceof HTMLElement ? options.mountEl : body
  let ele = document.createElement('div');
  let pending = false;
  
  mountEl.appendChild(ele);
  
  return new Promise((resolve, reject) => {
    createVue({
      el: ele,
      methods: {
        /** 取消  */
        cancel() {
          if(pending) return;
          
          pending = true;
          resolve({status: 1, message: 'cancel'});
        },
        /** 销毁  */
        destroy() {
          setTimeout(() => destroyComponent(this), 1500);
        },
        /** 值的改变  */
        input(user) {
          if (pending) return;
          
          pending = true;
          resolve({ status: 0, data: user });
        }
      },
      render() {
        return (
          <base-contact-department 
            max={max}
            selectedDept={selectedDepts}
            seeAllOrg={options.seeAllOrg || false}
            title={options.title || undefined}
            onDestroy={this.destroy.bind(this)}
            onCancel={this.cancel.bind(this)}
            onInput={this.input.bind(this)}
          >
          </base-contact-department>
        )
      },
      components: {
        [Department.name]: Department
      }
    })
  })
}

const BaseContact = {
  install(Vue) {
    fastCall(Vue, 'contact', { choose })
  },
  namespace: 'contact',
  props: {
    choose
  }
};

export default BaseContact;
